package org.vehicle.util;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.vehicle.vo.DataSourceRequest;

public class GridUtil {
	
	static String[] kendoRemoveField={
			"take","skip","filter[logic]"
	};//获取参数时，需要去除的参数
	
	/**
	 * 优化fill方法，只需要传入request即可
	 * @param request
	 * @return
	 */
	public static DataSourceRequest fill(HttpServletRequest request) {
		DataSourceRequest req = new DataSourceRequest();
		String page=request.getParameter("page");
		String pageSize=request.getParameter("pageSize");
		if(StringUtil.isNullOrEmpty(page)==false)
			req.setPage(1);
		else{
			req.setPage(Integer.parseInt(page));
		}
		if(StringUtil.isNullOrEmpty(pageSize)==false){
			req.setPageSize(10);
		}else{
			req.setPageSize(Integer.parseInt(pageSize));
		}
		Integer length=0;
		Boolean sortbool=false;
		@SuppressWarnings("rawtypes")
		Enumeration param = request.getParameterNames();
		while(param.hasMoreElements()){
			String field = (String) param.nextElement();
			if(field.contains("filter[filters]")){//获取条件
				length++;
			}else if(field.contains("sort[")){//获取排序字段  排序且只能根据一个列排序
				sortbool=true;
			}else{
				String value = request.getParameter(field);
				if (StringUtil.isNullOrEmpty(value)&&StringUtil.isNullOrEmpty(field)) {
					req.addObjData(field, value);
				}
			}
		}
		//length=length/2;
		for (int i = 0; i <length; i++) {
			String field = request.getParameter("filter[filters][" + i + "][field]");
			String value = request.getParameter("filter[filters][" + i + "][value]");
			if (StringUtil.isNullOrEmpty(value)&&StringUtil.isNullOrEmpty(field)) {
				req.addObjData(field, value);
			}
		}
		if(sortbool){
			String field = request.getParameter("sort[0][field]");
			String dir = request.getParameter("sort[0][dir]");
			if (StringUtil.isNullOrEmpty(dir)&&StringUtil.isNullOrEmpty(field)) {
				req.addObjData("kendosort"," order by "+field+" "+dir);
			}
		}
		for (int i = 0; i < kendoRemoveField.length; i++) {
			req.getData().remove(kendoRemoveField[i]);
		}
		req.addObjData("page", req.getPage());
		req.addObjData("pageSize", req.getPageSize());
		Integer start=(req.getPage()-1)*req.getPageSize();
		req.addObjData("start", start);
		req.addObjData("end", start+req.getPageSize());
		return req;
	}
	
}
